package com.wthink.hzgj.version

import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.DeviceVersion
import com.wthink.hzgj.service.DevService
import kotlinx.coroutines.*

class VersionViewModel :ViewModel(){

    val version = MutableLiveData(DeviceVersion("", ""))
    val ubusVersion = MutableLiveData("")

    fun getVersion(){
        getUbusVersion()
        version.postValue(
            getVersionName()?.let { DeviceVersion(""+ Build.VERSION.RELEASE, it) })
    }

    fun getVersionName(): String? {
        val packageManager: PackageManager = BusApplication.busContext.packageManager
        val packInfo: PackageInfo = packageManager.getPackageInfo("com.wthink.hzgj", 0)
        return packInfo.versionName
    }

    fun getUbusVersion(){
        GlobalScope.launch(Dispatchers.IO) {
                val verRet = DevService.queryAppVer()
                if (verRet is Result.Success) {
                    val busVer = verRet.data.bus_ver
                    ubusVersion.postValue(busVer)
                }
            }
    }
}